package de.hwr.it11.dectree.persistence;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.IOUtils;

/**
 * Der <code>CSVPersister</code> liest und schreibt CSV-Dateien.
 */
public class CSVPersister implements IPersister {

	@Override
	public List<List<String>> readFile(String pPath) throws IOException, ImportExportFailedException {
		List<List<String>> returnValue = new ArrayList<List<String>>();
		InputStream stream = null;

		try {
			stream = new FileInputStream(pPath);
			List<String> lines = IOUtils.readLines(stream);
			for (String line : lines) {
				String[] values = line.split(";", -1);
				List<String> valueList = new ArrayList<String>();
				for (String value : values) {
					valueList.add(value.isEmpty() ? null : value);
				}
				returnValue.add(valueList);
			}
			return returnValue;
		}
		finally {
			IOUtils.closeQuietly(stream);
		}
	}



	@Override
	public void writeFile(List<List<String>> pData, String pPath) throws IOException, ImportExportFailedException {
		OutputStream stream = null;
		List<String> writeList = new ArrayList<String>();

		try {
			stream = new FileOutputStream(pPath);
			for (List<String> rowData : pData) {
				StringBuilder builder = new StringBuilder();
				for (int i = 0; i < rowData.size(); i++) {
					String value = rowData.get(i);
					builder.append(value == null ? "" : value);
					if (i != rowData.size() - 1) {
						builder.append(";");
					}
				}
				writeList.add(builder.toString());
			}
			IOUtils.writeLines(writeList, null, stream);
		}
		finally {
			IOUtils.closeQuietly(stream);
		}
	}

}
